<?php

// [ 云片短信 ]
/*
use app\common\lib\Yp as YpCommonLib;
$yp  = new YpCommonLib;
$res = $yp->sendCode($mobile,$code);
$res = $yp->sendNotice($mobile,$password);
*/
/*
Array
(
    [code] => 0
    [msg] => 发送成功
    [count] => 1
    [fee] => 0.05
    [unit] => RMB
    [mobile] => 18123221961
    [sid] => 18388898834
)
*/

namespace app\common\lib;

class Yp
{
    protected $_apiKey = 'f1f0b18b2a223601631ba86c09ecf945';

    // 短信码
    public function sendCode($mobile, $code)
    {
        header("Content-Type:text/html;charset=utf-8");
        $url = 'https://sms.yunpian.com/v2/sms/single_send.json';
        $data = [
            'apikey' => $this->_apiKey,
            'mobile' => $mobile,
            'text'   => '【赛车计划】验证码：' . $code .'。',
        ];
        $res = $this->_https_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    // 通知
    public function sendNotice($mobile, $password)
    {
        header("Content-Type:text/html;charset=utf-8");
        $url = 'https://sms.yunpian.com/v2/sms/single_send.json';
        $data = [
            'apikey' => $this->_apiKey,
            'mobile' => $mobile,
            'text'   => '【赛车计划】您的帐号：' . $mobile . '，初始密码：' . $password . '，登录后请及时修改密码。',
        ];
        $res = $this->_https_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    // ------------------------------------------------------------------------------------------

    // 工具方法
    private function _https_curl($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, 
            array(
                'Accept:text/plain;charset=utf-8',
                'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'
            )
        );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($data) );
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}